home *** CD-ROM | disk | FTP | other *** search
- Path: news.ichange.com!newsmaster
- From: Jesse Liberty <jl@staff.ichange.com>
- Newsgroups: comp.lang.c++
- Subject: Re: References & Pointers in Borland C++
- Date: Tue, 12 Mar 1996 10:48:51 -0500
- Organization: AT&T
- Message-ID: <31459CE3.3A5D@staff.ichange.com>
- References: <4i26j5$roe@dfw-ixnews3.ix.netcom.com>
- NNTP-Posting-Host: 140.244.99.60
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 2.0 (Win95; I)
- CC: jl@staff.ichange.com
-
- Bob M wrote:
- >
- > I am trying to understand the concept of "References".
- >
- > But a couple of things are confusing me.
- >
- > 1.
- > The Programmer's manuals for Borland Turbo C++ version 1.01 (1990)
- > and Borland C++ version 4.02 describe in nearly identical text, that
- > it is acceptable to initialize a Reference with a specific number:
- > int& ir = 6;
- > Both my 3.1 and 4.02 compilers reject this with an error: "Reference
- > initialized with 'int' needs lvalue of type 'int'".
- > Which is right, the compiler or the book?
-
- The compiler is right. You can write
- const int& ir = 6;
-
- But having a non const integer reference would allow you later to write
-
- ir = 7;
-
- and what would that do? change the constant integer 6 to 7??
-
-
-
- >
- > 2.
- > Using the Inspector window in the Debugger, I could see that a
- > Reference appears identical to a pointer, except that the compiler
- > insists that you initialize it to some selected variable.
- > It looks as though one should be able to assign a "filled in"
- > pointer to a reference, as follows:
- > int num, nother;
- > int &ref1 = num, &ref2 = nother;
- > int *ptr1;
- >
- > ptr1 = &ref1; // sets the pointer to the same address as "num".
- > &ref2 = ptr1; // Change &ref2 to point at "num".
- >
- > The first assignment is apparently legal, but the second depends
- > on the version of the compiler. 3.1 accepts it, while 4.01 says:
- > "Lvalue required in function main".
- > Should this be legal?
-
- Right, because your first line is not doing what you think. When you write
-
- ptr1 = &ref1;
-
- what you are really writing is
-
- ptr1 = # // remember ref1 is an alias to num
-
- which is perfectly legal.
-
- When you then write
-
- &ref2 = ptr1;
-
- What you are really writing is
-
- ¬her = ptr1;
-
- This is not legal, you can't assign to the address of a variable.
-
-
- The fact that references are generally implemented using pointers is irrelevant; they are a different data type with explicit
- rules.
-